package com.neo.sk.collector

import akka.actor.{Actor, Props}
import com.neo.sk.common._
import com.neo.sk.util.ParseUtil
import com.neo.sk.util.http.HttpClientUtil
import org.slf4j.LoggerFactory

import scala.concurrent.Future
import scala.concurrent.duration._
import scala.util.{Failure, Success}
/**
 * User: huangshanqi
 * Date: 2015/7/12
 * Time: 20:38
 */
class MovieTagFetchActor extends Actor{
  private val logger = LoggerFactory.getLogger(this.getClass)

  import com.neo.sk.collector.Manager.myExecutionContext
  val saveActor = context.actorOf(Props[SaveActor](new SaveActor), "SaveActor-" + System.currentTimeMillis())
  final val httpClientUtil = new HttpClientUtil()
  private final val fetchTagUrl = "http://movie.douban.com/tag/?view=cloud&retry=1"
  private final val maxRetryTime = 3

  override def receive: Receive = {
    case UrlTask(url) =>{
      logger.info("Tick in fetch movie tag...........................")
      val urlStrings = url.split("retry=")
      val retryTime = urlStrings(1).toInt
      if(retryTime < maxRetryTime){
        val f = Future {
          httpClientUtil.getResponseContent(url,"utf-8")
        }
        f.onComplete {
          case Success(content) => {
            if (content != null && content != "") {
              val result = ParseUtil.parseTagHtml(content)
              if(result!=null && result.size>0){
                saveActor ! SaveTagList(result)
              }else{
                val retryUrl = urlStrings(0) + "retry=" + (retryTime + 1)
                self ! Retry(retryUrl)
              }
            } else {
              val retryUrl = urlStrings(0) + "retry=" + (retryTime + 1)
              self ! Retry(retryUrl)
            }
          }
          case Failure(e) =>{
            val retryUrl = urlStrings(0) + "retry=" + (retryTime + 1)
            self ! Retry(retryUrl)
          }
        }
      }else{
        logger.info("get url:" + url + " more than " + maxRetryTime +" times and fail")
      }

    }
    case Retry(url) =>{
      context.system.scheduler.scheduleOnce(5 seconds,self,UrlTask(url))
    }
    case unknow@_ => logger.info("unknow message: "+ unknow + "  in " + context.self.path.name + " from " + context.sender().path.name)
  }
}
